//
//  MYPublishAlbumVC.m
//  MuYing
//
//  Created by tbb on 2019/8/12.
//  Copyright © 2019 TBB. All rights reserved.
//

#import "MYPublishAlbumVC.h"
#import "TZImageManager.h"
#import "TZImageManager.h"
#import "YQImagePickerBaseVC.h"
#import "YQBaseCollectionView.h"
#import "TZAssetCell.h"
#import "TZAssetModel.h"
#import "TZImageRequestOperation.h"
#import "SDCycleScrollView.h"
#import "MYPublishImageTagVC.h"
#import "MYPublishEditVC.h"
//#import "YBImageBrowser.h"
#define itemMargin 7.0
#define itemWH (kYQPScreenWidth - 5 * itemMargin) / 4.0
#define collectionViewH (2*itemWH +itemMargin)
@interface MYPublishAlbumVC ()<UICollectionViewDelegate,UICollectionViewDataSource,SDCycleScrollViewDelegate>
@property (nonatomic, strong) NSMutableArray * albumModelArr;
@property (nonatomic, strong) NSMutableArray * selectModelArr;
@property (nonatomic, strong) NSMutableArray * selectImageArr;
@property (nonatomic, strong) NSMutableArray * selectedAssetIds;


@property (nonatomic, strong) YQBaseCollectionView *collectionView;
@property (strong, nonatomic) UICollectionViewFlowLayout *layout;

@property (nonatomic, strong) NSOperationQueue *operationQueue;

@property (nonatomic, strong) SDCycleScrollView * imageBrowser;

@property (nonatomic, strong) NSMutableDictionary * imageUrlDict;

@end

@implementation MYPublishAlbumVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = HexColor(0xFAFAFA);
//    self.listTableView.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - 44-49-kHeight_Botton_SafeArea);
    [self.view addSubview:self.collectionView];
    [self.view addSubview:self.imageBrowser];
    self.collectionView.frame = CGRectMake(7, CGRectGetMaxY(self.imageBrowser.frame)+12, kYQPScreenWidth-14, collectionViewH);
    YQImagePickerBaseVC *imagePickerVc = [[YQImagePickerBaseVC alloc] initWithMaxImagesCount:9 delegate:nil];
    [self fetchAssetModels];
}
-(void)setupView {
    [super setupView];
    self.view.backgroundColor = HexColor(0xFAFAFA);
}
-(YQBaseCollectionView *)collectionView {
    if (!_collectionView) {
        _layout = [[UICollectionViewFlowLayout alloc] init];
        _layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        _layout.itemSize = CGSizeMake(itemWH, itemWH);
        _layout.minimumInteritemSpacing = itemMargin;
        _layout.minimumLineSpacing = itemMargin;
        _collectionView = [[YQBaseCollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_layout];
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.alwaysBounceHorizontal = NO;
        _collectionView.contentInset = UIEdgeInsetsMake(14, 0, 14, 0);
        [_collectionView registerClass:[TZAssetCell class] forCellWithReuseIdentifier:@"TZAssetCell"];
    }
    return _collectionView;
}

- (void)fetchAssetModels {
    if (![[TZImageManager manager] authorizationStatusAuthorized]) {
        return;
    }
    
    [TZImageManager manager].sortAscendingByModificationDate = NO;
    [TZImageManager manager].columnNumber = 4;
    ws(self);
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        if (!self.albumModel) {
            [[TZImageManager manager] getCameraRollAlbum:YES allowPickingImage:YES needFetchAssets:YES completion:^(TZAlbumModel *model) {
                self->_albumModel = model;
                self->_albumModelArr = [NSMutableArray arrayWithArray:self->_albumModel.models];
                dispatch_async(dispatch_get_main_queue(), ^{
                   [self->_collectionView reloadData];
                });
            }];
        }else{
            if (self.albumModel.models.count > 0) {
                self->_albumModelArr = [NSMutableArray arrayWithArray:self->_albumModel.models];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakself.collectionView reloadData];
                });
            }else{
                [[TZImageManager manager] getAssetsFromFetchResult:self->_albumModel.result completion:^(NSArray<TZAssetModel *> *models) {
                    self->_albumModelArr = [NSMutableArray arrayWithArray:models];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakself.collectionView reloadData];
                    });
                }];
            }
        }
    });
}
#pragma mark --<UICollectionViewDelegate,UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.albumModelArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    // the cell dipaly photo or video / 展示照片或视频的cell
    TZAssetModel *assetModel = nil;
    if (indexPath.item < self.albumModelArr.count) {
        assetModel = self.albumModelArr[indexPath.item];
    }
    TZAssetCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TZAssetCell" forIndexPath:indexPath];
    cell.contentView.layer.cornerRadius = 4;
    //默认为NO，为YES时可以多选视频/gif/图片，和照片共享最大可选张数maxImagesCount的限制 album_number_icon
    cell.allowPickingMultipleVideo = NO;
    cell.allowPickingGif = NO;
    UIImage *photoSelImage = [UIImage tz_imageNamedFromMyBundle:@"album_number_icon"];
    cell.photoSelImage = [photoSelImage qmui_imageWithBlendColor:kAPPThemeColor];
    cell.photoDefImage = YQIMG(@"album_def_photoPickerVc");
    
    cell.model = assetModel;
    //默认为NO，如果设置为YES，会显示照片的选中序号
    cell.assetCellDidSetModelBlock = ^(TZAssetCell *cell, UIImageView *imageView, UIImageView *selectImageView, UILabel *indexLabel, UIView *bottomView, UILabel *timeLength, UIImageView *videoImgView) {
        indexLabel.font = kSystemMedium(10);
    };
    if (assetModel.isSelected) {
        cell.index = [self.selectedAssetIds indexOfObject:assetModel.asset.localIdentifier] + 1;
    }
    cell.showSelectBtn = YES;
    cell.allowPreview = YES;
    cell.cannotSelectLayerButton.hidden = YES;
    
    UILabel *indexLb = [cell valueForKey:@"indexLabel"];
    
    __weak typeof(cell) weakCell = cell;
    __weak typeof(indexLb) weakindexLb = indexLb;
    __weak typeof(self) weakSelf = self;

    cell.didSelectPhotoBlock = ^(BOOL isSelected) {
        __strong typeof(weakCell) strongCell = weakCell;
        __strong typeof(weakindexLb) strongindexLb = weakindexLb;
        __strong typeof(weakSelf) strongSelf = weakSelf;
        // 1. cancel select / 取消选择
        if (isSelected) {
            strongCell.selectPhotoButton.selected = NO;
            assetModel.isSelected = NO;
            [strongSelf removeSelectedModel:assetModel];
            [strongSelf.collectionView reloadData];
        }else{
            assetModel.isSelected = YES;
            strongCell.selectPhotoButton.selected = YES;
            [strongSelf addSelectedModel:assetModel];
            strongCell.index = self.selectedAssetIds.count;
        }
        strongindexLb.hidden = !assetModel.isSelected;
    };
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"");
}
#pragma mark --<UICollectionViewDelegate,UICollectionViewDataSource> end
- (void)addSelectedModel:(TZAssetModel *)model {
    if (![self.imageUrlDict.allKeys containsObject:model.asset.localIdentifier]) {
        TZImageRequestOperation *operation = [[TZImageRequestOperation alloc] initWithAsset:model.asset completion:^(UIImage * _Nonnull photo, NSDictionary * _Nonnull info, BOOL isDegraded) {
            if (isDegraded) return;
            if (photo) {
                if (![TZImagePickerConfig sharedInstance].notScaleImage) {
                    photo = [[TZImageManager manager] scaleImage:photo toSize:CGSizeMake(414, (int)(414 * photo.size.height / photo.size.width))];
                }
                
                YQSHOWLOADINGINVIEW
                [YQPImageUploader sendPOSTWithUrl:kPOST_FILE_UPLOAD_URL withLocalImage:photo isNeedToken:YES parameters:@{} success:^(id  _Nullable responseObject) {
                    YQHIDELOADINGTIPS
                    //[MBProgressHUD showMessage:@"上传成功"];
                    self.imageUrlDict[model.asset.localIdentifier] = responseObject[@"data"];
                } fail:^(NSError * _Nullable error) {
                    YQHIDELOADINGTIPS
                }];
                
            }
        } progressHandler:^(double progress, NSError * _Nonnull error, BOOL * _Nonnull stop, NSDictionary * _Nonnull info) {

        }];
        [self.operationQueue addOperation:operation];
    }
    [self.selectModelArr addObject:model];
    [self.selectedAssetIds addObject:model.asset.localIdentifier];
    [self ImageRequestOperationAction];
}

- (void)removeSelectedModel:(TZAssetModel *)model {
    [self.selectModelArr removeObject:model];
    [self.selectedAssetIds removeObject:model.asset.localIdentifier];
    //[self.imageUrlDict removeObjectForKey:model.asset.localIdentifier];
    
    [self ImageRequestOperationAction];
}

-(void)ImageRequestOperationAction{
    if (self.selectModelArr.count == 0) {
        self.imageBrowser.localizationImageNamesGroup = nil;
    }
    NSMutableArray *photos = [NSMutableArray array];
    NSMutableArray *infoArr = [NSMutableArray array];
    NSMutableArray *assets = [NSMutableArray array];
    __block BOOL havenotShowAlert = YES;
    [TZImageManager manager].shouldFixOrientation = YES;
    __block UIAlertController *alertView;
    for (NSInteger i = 0; i < self.selectModelArr.count; i++) { [photos addObject:@1];[assets addObject:@1];[infoArr addObject:@1]; }
    for (NSInteger i = 0; i < self.selectModelArr.count; i++) {
        TZAssetModel *model = self.selectModelArr[i];
        
        TZImageRequestOperation *operation = [[TZImageRequestOperation alloc] initWithAsset:model.asset completion:^(UIImage * _Nonnull photo, NSDictionary * _Nonnull info, BOOL isDegraded) {
            if (isDegraded) return;
            if (photo) {
                if (![TZImagePickerConfig sharedInstance].notScaleImage) {
                    photo = [[TZImageManager manager] scaleImage:photo toSize:CGSizeMake(414, (int)(414 * photo.size.height / photo.size.width))];
                }
                [photos replaceObjectAtIndex:i withObject:photo];
            }
           
            [photos replaceObjectAtIndex:i withObject:photo];
            if (info)  [infoArr replaceObjectAtIndex:i withObject:info];
            [assets replaceObjectAtIndex:i withObject:model.asset];
            
            for (id item in photos) { if ([item isKindOfClass:[NSNumber class]]) return; }
            
            if (havenotShowAlert) {
                self.imageBrowser.localizationImageNamesGroup = photos.copy;
                self.selectImageArr = [NSMutableArray arrayWithArray:photos.copy];
//                [tzImagePickerVc hideAlertView:alertView];
//                [self didGetAllPhotos:photos assets:assets infoArr:infoArr];
            }
        } progressHandler:^(double progress, NSError * _Nonnull error, BOOL * _Nonnull stop, NSDictionary * _Nonnull info) {
            // 如果图片正在从iCloud同步中,提醒用户
            if (progress < 1 && havenotShowAlert && !alertView) {
//                [tzImagePickerVc hideProgressHUD];
//                alertView = [tzImagePickerVc showAlertWithTitle:[NSBundle tz_localizedStringForKey:@"Synchronizing photos from iCloud"]];
                havenotShowAlert = NO;
                return;
            }
            if (progress >= 1) {
                havenotShowAlert = YES;
            }
        }];
        [self.operationQueue addOperation:operation];
        
    }
}
#pragma mark--SDCycleScrollViewDelegate
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    if (self.selectModelArr.count == 0) {
        return;
    }

}

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didScrollToIndex:(NSInteger)index {
    
}
#pragma mark--SDCycleScrollViewDelegate end
#pragma mark - JXCategoryListContentViewDelegate

- (UIView *)listView {
    return self.view;
    
}
- (UIScrollView *)listScrollView {
    return self.collectionView;
}
#pragma mark - JXCategoryListContentViewDelegate end
-(void)setAlbumModel:(TZAlbumModel *)albumModel {
    _albumModel = albumModel;
    [self.selectedAssetIds removeAllObjects];
    [self.selectModelArr removeAllObjects];
    [self.albumModelArr removeAllObjects];
    [self.selectImageArr removeAllObjects];
    self.imageBrowser.localizationImageNamesGroup = nil;
    [self fetchAssetModels];
}

#pragma amkr --lazy
-(NSMutableArray *)albumModelArr {
    if (!_albumModelArr) {
        _albumModelArr = [NSMutableArray array];
    }
    return _albumModelArr;
}
-(NSMutableArray *)selectModelArr {
    if (!_selectModelArr) {
        _selectModelArr = [NSMutableArray array];
    }
    return _selectModelArr;
}
-(NSMutableArray *)selectedAssetIds {
    if (!_selectedAssetIds) {
        _selectedAssetIds = [NSMutableArray array];
    }
    return _selectedAssetIds;
}

-(NSOperationQueue *)operationQueue {
    if (!_operationQueue) {
        _operationQueue = [[NSOperationQueue alloc] init];
        _operationQueue.maxConcurrentOperationCount = 4;
    }
    return _operationQueue;
}

-(SDCycleScrollView *)imageBrowser {
    if (!_imageBrowser) {
        _imageBrowser = [[SDCycleScrollView alloc] initWithFrame:CGRectMake(0, 0, kYQPScreenWidth, kYQPScreenHeight- collectionViewH -49-kHeight_Botton_SafeArea-44-12-kHeight_Top_SafeArea)];
        _imageBrowser.showPageControl= false;
//        _imageBrowser.placeholderImage = YQIMG(@"Test_Rectangle_icon");
        _imageBrowser.pageControlStyle = SDCycleScrollViewPageContolStyleAnimated;
        _imageBrowser.bannerImageViewContentMode = UIViewContentModeScaleAspectFill;
        _imageBrowser.clipsToBounds = true;
        _imageBrowser.infiniteLoop = false;
        _imageBrowser.autoScroll = false;
        _imageBrowser.delegate = self;
        _imageBrowser.backgroundColor = kAPPThemeColor;
        
    }
    return _imageBrowser;
}
-(NSMutableDictionary *)imageUrlDict {
    if (!_imageUrlDict) {
        _imageUrlDict = [NSMutableDictionary dictionary];
    }
    return _imageUrlDict;
}
#pragma amkr --lazy end
-(void)nextAction {
    if (self.selectModelArr.count == 0) {
        [QMUITips showError:kYQLS(@"请选择图片") inView:self.view hideAfterDelay:1];
        return;
    }
    
    NSMutableArray *urlArr = @[].mutableCopy;
    
    for (TZAssetModel *assetModel in self.selectModelArr) {
        [urlArr addObject:self.imageUrlDict[assetModel.asset.localIdentifier]];
    }
    
    MYPublishEditVC *editVC = [[MYPublishEditVC alloc] init];
    editVC.publishImageArr = self.selectImageArr.copy;
    editVC.publishImageUrlArr = urlArr.copy;
    [self.navigationController pushViewController:editVC animated:true];
#warning mark --暂时不用加标签
//    MYPublishImageTagVC *tagVC = [[MYPublishImageTagVC alloc] init];
//    tagVC.publishImageArr = self.selectImageArr.copy;
//    kYQPUSH(tagVC);
    
}
@end
